/**
 * Created by julia.zhou on 2016/5/12.
 */
define(['jquery', 'appLocalStorage', 'appConst', 'model/global', 'common/widgetUtils', 'model/report', 'stringUtils', 'appMessageBox', 'domReady!'], function ($, appLocalStorage, appConst, global, widgetUtils, report, stringUtils, msgBox) {
    var that;
    var projectName = "";
    var components = {};
    var flagTag = {
        item: true,
        attribute: true
    };
    var data = {
        searchFields: {},
        searchYieldParams: {},
        searchYieldSnParams: {},
        searchYieldItemParams: {},
        yieldDatas: {},
        yieldAttributeDatas: {}
    };
    return {
        init: function () {
            that = this;
            components = {
                "tbl_yield": $("#tbl_yield"),
                "tbl_yieldSn": $("#tbl_yieldSn"),
                "tbl_yieldItems": $("#tbl_yieldItems"),
                "tbl_yieldAttributes": $("#tbl_yieldAttributes"),
                "wgt_report": $("#wid-id-0"),
                "yield_collapseBtn1": $("#yield_collapseBtn1"),
                "yield_collapseBtn2": $("#yield_collapseBtn2"),
                "yield_collapseBtn3": $("#yield_collapseBtn3"),
                "export_yields": $("#exportYields"),
                "export_yieldsn": $("#exportYieldSn"),
                "export_yield_items": $("#exportYieldItems"),
                "tag_itemsOrAttributes": $("#tag_itemsOrAttributes"),
                "toggleTab": $('a[data-toggle="tab"]'),
                "tag_items": "tag_items",
                "tag_attributes":"tag_attributes"
            };
            that.initYieldTable();
            that.initYieldSnTable();
            that.initYieldItemsTable();
            that.initYieldAttributesTable();
            that.initYieldExport();
            that.resetYield();
        },
        closeCollapse: function (collapseObj) {
            var theOthers = collapseObj.parent('div').nextAll("div, ul");
            var img = collapseObj.find('span > i');
            if (theOthers.is(":hidden")) {
                img.removeClass('fa-angle-down');
                img.addClass('fa-angle-left');
            }
            else {
                img.removeClass('fa-angle-down');
                img.addClass('fa-angle-left');
                theOthers.toggle();
            }
        },
        openCollapse: function (collapseObj) {
            var theOthers = collapseObj.parent('div').nextAll("div, ul");
            var img = collapseObj.find('span > i');

            if (theOthers.is(":hidden")) {
                img.removeClass('fa-angle-left');
                img.addClass('fa-angle-down');
                theOthers.toggle();
            }
            else {
                img.removeClass('fa-angle-left');
                img.addClass('fa-angle-down');
            }
        },
        initYieldTable: function () {
            components.tbl_yield.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing":true,
                "paging": true,
                "autoWidth": false,
                "stateSave": true,
                "language": appConst.table_language(),
                "ordering": false,
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets":[2],
                        "render":function (data, type, full) {
                            return (data == null? '-':(data == ""?'-':(type === 'display' && data.length > 15 ?
                            '<span title="'+data+'">' + data.substr(0, 12) + '...</span>' :data)));
                        }
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='0' data-value='" + data + "' class='firstInspect'>" + data + "</a><a href='javascript:void(0);'data-stationId='"+ dataId +"' data-type='0' data-value='" + data + "' class='firstInspect'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='1' data-value='" + data + "' class='firstPass'>" + data + "</a><a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='1' data-value='" + data + "' class='firstPass'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='2' data-value='" + data + "' class='firstFail'>" + data + "</a><a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='2' data-value='" + data + "' class='firstFail'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [6],
                        "render": function (data, type, full) {
                            return data + "%";
                        }
                    },
                    {
                        "targets": [7],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='3' data-value='" + data + "' class='reInspect'>" + data + "</a><a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='3' data-value='" + data + "' class='reInspect'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [8],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='4'  data-value='" + data + "' class='rePass'>" + data + "</a><a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='4' data-value='" + data + "' class='rePass'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [9],
                        "render": function (data, type, full) {
                            var dataId = full[2];
                            var url = "<a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='5' data-value='" + data + "' class='reFail'>" + data + "</a><a href='javascript:void(0);' data-stationId='"+ dataId +"' data-type='5' data-value='" + data + "' class='reFail'>" + "<i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [10],
                        "render": function (data, type, full) {
                            return data + "%";
                        }
                    },
                    {
                        "targets": [11],
                        "render": function (data, type, full) {
                            return data + "%";
                        }
                    }
                ]
            });
            global.drawNumber_ui(components.tbl_yield);

            that.yieldEventDelegate(".firstInspect");
            that.yieldEventDelegate(".firstPass");
            that.yieldEventDelegate(".firstFail");

            that.yieldEventDelegate(".reInspect");
            that.yieldEventDelegate(".rePass");
            that.yieldEventDelegate(".reFail");
        },
        yieldEventDelegate: function (target) {
            components.tbl_yield.delegate(target, "click", function () {
                var obj = {
                    search_EQ_stationId: $(this).attr("data-stationId"),
                    search_EQ_type: $(this).attr("data-type")
                };
                that.resetYieldSn($(this));
                that.loadYieldSnTable(obj);
            });
        },
        loadYieldData: function (fileds) {
            that.resetYield();
            data.searchFields = fileds;
            projectName = data.searchFields.search_projectName;
            var searchParam = {
                "search_EQ_stationIdOrSlotNo": data.searchFields.search_stationIdOrSlotNo,
                "search_EQ_projectId": data.searchFields.search_projectId,
                "search_EQ_projectName": data.searchFields.search_projectName,
                "search_EQ_serialNumber": data.searchFields.search_serialNumber,
                "search_GTE_startTime": data.searchFields.search_startTime,
                "search_LTE_stopTime": data.searchFields.search_stopTime
            };
            data.searchYieldParams = searchParam;
            widgetUtils.toggleWidgetLoading(components.wgt_report);
            report.searchYields(searchParam, function (d) {
                data.yieldDatas = [];
                var array = new Array();
                $(d).each(function (i, e) {
                    var arr = new Array();
                    arr.push(null);
                    arr.push(e.id);
                    arr.push(e.stationName);
                    arr.push(e.firstInspect);
                    arr.push(e.firstPass);
                    arr.push(e.firstFail);
                    arr.push(e.fpy);
                    arr.push(e.reTestInspect);
                    arr.push(e.reTestPass);
                    arr.push(e.reTestFail);
                    arr.push(e.reTestYield);
                    arr.push(e.totalYield);
                    array.push(arr);
                });
                data.yieldDatas = array;
                components.tbl_yield.dataTable().api().clear().draw();
                components.tbl_yield.dataTable().api().rows.add(data.yieldDatas).draw();
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            },
                function (d) {
                    widgetUtils.toggleWidgetLoading(components.wgt_report);
                });
        },

        initYieldSnTable: function () {
            var customParams = function (params) {
                $.extend(params, data.searchYieldSnParams);
                params['draw'] = params.draw;
                return params;
            };

            components.tbl_yieldSn.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing":true,
                "pageLength": 10,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "stateSave": false,
                "ordering": false,
                "language": appConst.table_language(),
                "ajax": {
                    "url": 'empty',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": customParams,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                        widgetUtils.toggleWidgetLoading(components.wgt_report);
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "idStr"},
                    {"data": "serialNumber"},
                    {"data": "projectName"},
                    {"data": "stationId"},
                    {"data": "slotNo"},
                    {"data": "startTime"},
                    {"data": "stopTime"},
                    {"data": "isPass"}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [2],
                        "render": function (data, type, full) {
                            var url = "<a href='javascript:void(0);' data-id='"+ full.idStr +"' data-sn='"+ data +"' class='yieldSn'>"+(type === 'display' && data.length > 20 ?
                                '<span title="'+data+'">' + data.substr(0, 18) + '...</span>' :data)+"</a><a href='javascript:void(0);' data-id='"+ full.idStr +"' data-sn='"+ data +"' class='yieldSn'><i class='fa fa-search pull-right'" +
                                "rel='tooltip' data-placement='right' data-original-title='"+ $.i18n.prop('REPORT_DETAIL_TIP') +"' data-html='true'/></a>";
                            return url;
                        }
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            return type === 'display' && data.length > 20 ?
                            '<span title="'+data+'">' + data.substr(0, 18) + '...</span>' :data;
                        }
                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            return data == null?'-':(type === 'display' && data.length > 15 ?
                            '<span title="'+data+'">' + data.substr(0, 13) + '...</span>' :data);
                        }
                    },
                    {
                        "targets": [6],
                        "render": function (data, type, full) {
                            return data;
                        }
                    }, {
                        "targets": [7],
                        "render": function (data, type, full) {
                            return data;

                        }
                    },
                    {
                        "targets": [8],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = '<span class="label label-success">'+ $.i18n.prop('REPORT_PASS') +'</span>';
                            } else if (data == false) {
                                result = '<span class="label label-danger">'+ $.i18n.prop('REPORT_FAIL') +'</span>';
                            }
                            return result;
                        }
                    }
                ],
                "initComplete":function() {
                    $("[rel=tooltip]").tooltip();
                }
            });
            global.drawNumber_bg(components.tbl_yieldSn);
            that.yieldSnTbodyClickEvent(components.tbl_yieldSn);
        },
        loadYieldSnTable: function (obj) {
            var stations = new Array();
            var s = {'stationId': obj.search_EQ_stationId, 'slotNos': []};
            var queryParameter = JSON.parse(data.searchFields.search_stationIdOrSlotNo);
            $.each(queryParameter, function (i, data) {
                if (data.stationId == obj.search_EQ_stationId) {
                    s.slotNos = data.slotNos;
                    return false;
                }
            });
            stations.push(s);
            var searchParam = {
                "search_EQ_stationIdOrSlotNo": JSON.stringify(stations),
                "search_EQ_projectId": data.searchFields.search_projectId,
                "search_EQ_projectName": data.searchFields.search_projectName,
                "search_EQ_serialNumber": data.searchFields.search_serialNumber,
                "search_GTE_startTime": data.searchFields.search_startTime,
                "search_LTE_stopTime": data.searchFields.search_stopTime,
                'search_EQ_type': obj.search_EQ_type
            };
            data.searchYieldSnParams = searchParam;

            widgetUtils.toggleWidgetLoading(components.wgt_report);
            components.tbl_yieldSn.DataTable().ajax.url("yield/queryHistoryYield").load(function () {
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            });
        },
        initYieldItemsTable: function () {
            var customParams = function (params) {
                $.extend(params, data.searchYieldItemParams);
                params['draw'] = params.draw;
                return params;
            };
            components.tbl_yieldItems.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": true,
                "ordering": false,
                "ajax": {
                    "url": 'empty',
                    "type": "POST",
                    "dataSrc": "body",
                    "data": customParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                        widgetUtils.toggleWidgetLoading(components.wgt_report);
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "name"},
                    {"data": "upperLimit"},
                    {"data": "lowerLimit"},
                    {"data": "unitName"},
                    {"data": "testedValue"},
                    {"data": "isPass"}
                ],
                "columnDefs": [
                    {
                        "targets": [6],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = '<span class="label label-success">' + $.i18n.prop('REPORT_PASS') + '</span>';
                            } else if (data == false) {
                                result = '<span class="label label-danger">' + $.i18n.prop('REPORT_FAIL') + '</span>';
                            }
                            return result;
                        }
                    }
                ],
                "initComplete": function () {
                    $("[rel=tooltip]").tooltip();
                }
            });
            global.drawNumber_bg(components.tbl_yieldItems);

        },
        loadYieldItemsData: function (id, sn) {
            var searchParams = {
                "search_EQ_projectId": data.searchFields.search_projectId,
                "search_EQ_serialNumber": sn,
                'search_EQ_id': id
            };
            data.searchYieldItemParams = searchParams;

            widgetUtils.toggleWidgetLoading(components.wgt_report);
            components.tbl_yieldItems.DataTable().ajax.url("yield/queryItemYield").load(function () {
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            });
        },
        initYieldAttributesTable: function () {
            components.tbl_yieldAttributes.dataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing":true,
                "paging": true,
                "autoWidth": false,
                "stateSave": true,
                "language": appConst.table_language(),
                "ordering": false
            });
            global.drawNumber_ui(components.tbl_yieldAttributes);
        },
        loadYieldAttributesData: function (sn) {
            var searchParams = {
                "search_EQ_projectId": data.searchFields.search_projectId,
                "search_EQ_serialNumber": sn
            };

            widgetUtils.toggleWidgetLoading(components.wgt_report);
            report.searchAttributes(searchParams, function (d) {
                data.yieldAttributeDatas = [];
                var array = new Array();
                $(d).each(function (i, e) {
                    var arr = new Array();
                    arr.push(null);
                    arr.push(e.attributeName);
                    arr.push(e.attributeValue);
                    array.push(arr);
                });
                data.yieldAttributeDatas = array;
                components.tbl_yieldAttributes.dataTable().api().clear().draw();
                components.tbl_yieldAttributes.dataTable().api().rows.add(data.yieldAttributeDatas).draw();
                widgetUtils.toggleWidgetLoading(components.wgt_report);
            },
                function (d) {
                    widgetUtils.toggleWidgetLoading(components.wgt_report);
                });
        },
        initYieldExport: function () {
            components.export_yields.click(function () {
                var params = stringUtils.getExportParams(data.searchYieldParams);
                if(params != "" && params != null){
                    $(this).attr("href", "report/yieldView/xls?" + params);
                }
            });

            components.export_yieldsn.click(function () {
                var params = stringUtils.getExportParams(data.searchYieldSnParams);
                if(params != "" && params != null){
                    $(this).attr("href", "report/yieldViewHistory/xls?" + params);
                }

            });

            components.export_yield_items.click(function () {
                var params = stringUtils.getExportParams(data.searchYieldItemParams);
                if(params != "" && params != null){
                    $(this).attr("href", "report/yieldViewTestItem/xls?" + params);
                }
            });
        },
        yieldSnTbodyClickEvent: function (table) {
            table.find('tbody').on('click', 'tr', function () {
                var target = $(this).find("td").children(".yieldSn");
                that.resetYieldItem(target);
                that.initItemActiveTab(target.attr("data-id"), target.attr("data-sn"));
            });
        },
        initItemTab: function (id, sn) {
            var itemId = "#"+components.tag_items;
            var attributeId = "#"+components.tag_attributes;
            components.toggleTab.on('shown.bs.tab', function (e) {
                if (($(this).attr("href") == itemId) && (flagTag.item)) {
                    that.loadYieldItemsData(id, sn);
                    flagTag.item = false;
                } else if (($(this).attr("href") == attributeId) && (flagTag.attribute)) {
                    that.loadYieldAttributesData(sn);
                    flagTag.attribute = false;
                }
            });
        },
        initItemActiveTab: function (id, sn) {
            flagTag.item = true;
            flagTag.attribute = true;
            var itemId = "#"+components.tag_items;
            var attributeId = "#"+components.tag_attributes;
            if (components.tag_itemsOrAttributes.find(".active").find("a").attr("href") == itemId) {
                if (id != null && id != "") {
                    that.loadYieldItemsData(id, sn);
                    flagTag.item = false;
                }
            } else if (components.tag_itemsOrAttributes.find(".active").find("a").attr("href") == attributeId) {
                if (sn != null && sn != "") {
                    that.loadYieldAttributesData(sn);
                    flagTag.attribute = false;
                }
            }
            that.initItemTab(id, sn);
        },
        resetYield: function () {
            data.yieldDatas = {};
            data.yieldAttributeDatas = {};
            appConst.clearTable(components.tbl_yieldSn);
            appConst.clearTable(components.tbl_yieldItems);

            components.yield_collapseBtn2.parent().parent().find("strong").parent().remove();
            components.yield_collapseBtn3.parent().parent().find("strong").parent().remove();

            that.openCollapse(components.yield_collapseBtn1);
            that.closeCollapse(components.yield_collapseBtn2);
            that.closeCollapse(components.yield_collapseBtn3);

        },
        resetYieldSn: function (target) {
            data.yieldAttributeDatas = {};

            appConst.clearTable(components.tbl_yieldSn);
            appConst.clearTable(components.tbl_yieldItems);

            target.parent().parent().addClass("active");
            target.parent().parent().siblings().removeClass("active");
            components.yield_collapseBtn2.parent().parent().find("strong").parent().remove();
            components.yield_collapseBtn3.parent().parent().find("strong").parent().remove();
            components.yield_collapseBtn2.parent().append('<span> '+$.i18n.prop("REPORT_STATIONNAME")+': <strong>'+ target.attr("data-stationId") + '</strong>&nbsp;&nbsp;&nbsp;&nbsp;'+ $.i18n.prop('REPORT_'+ target.attr("data-type")) +': <strong>'+ target.attr("data-value") +'</strong></span>');

            that.openCollapse(components.yield_collapseBtn2);
            that.closeCollapse(components.yield_collapseBtn3);
        },
        resetYieldItem: function (target) {
            target.parent().parent().addClass("active");
            target.parent().parent().siblings().removeClass("active");
            components.yield_collapseBtn3.parent().parent().find("strong").parent().remove();
            components.yield_collapseBtn3.parent().append('<span> '+$.i18n.prop("REPORT_SERIALNUMBER")+': <strong>'+ target.attr("data-sn") + '</strong></span>');

            that.openCollapse(components.yield_collapseBtn3);
        }
    };
});